package com.example.multi.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.example.multi.config.Config;
import com.example.multi.config.ExecutorConstant;
import com.example.multi.entity.Resp;
import com.example.multi.entity.User;
import com.example.multi.service.IUserService;
import com.example.multi.util.WebUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Future;

@Slf4j
@Service
public class UserService implements IUserService {


    @Override
    public List<Integer> listUserId(){
        //使用httpUtil 模拟 feign请求服务接口 start
        String reqUrl = Config.baseUrl.concat("/v1/user/list");
        HttpRequest httpRequest = HttpUtil.createGet(reqUrl);
        //设置请求头信息
        String token = WebUtil.getCurrentRequestHeaderToken();
        httpRequest.header("token",token);
        HttpResponse httpResponse = httpRequest.execute();

        String body = httpResponse.body();
        Resp<List<Integer>> respData = JSONUtil.toBean(body, Resp.class);
        //使用httpUtil 模拟 feign请求服务接口 end
        if(respData.isSuccess()){
            return respData.getData();
        }
        return null;
    };

    @Override
    public User getUser(Integer userId){

        //使用httpUtil 模拟 feign请求服务接口 start
        String reqUrl = StrUtil.format(Config.baseUrl.concat("/v1/user/get?userId={}"),userId);
        HttpRequest httpRequest = HttpUtil.createGet(reqUrl);
        //设置请求头信息
        String token = WebUtil.getCurrentRequestHeaderToken();
        httpRequest.header("token",token);
        HttpResponse httpResponse = httpRequest.execute();

        String body = httpResponse.body();
        Gson gson = new Gson();
        Resp<User> respData = gson.fromJson(body , new TypeToken<Resp<User>>(){}.getType());
        //使用httpUtil 模拟 feign请求服务接口 end
        if(respData.isSuccess()){
            return respData.getData();
        }
        return null;
    };


    @Override
    public List<User> listUser_1(){
        //获取用户列表 start
        List<User> userList = new ArrayList<>();
        List<Integer> userIds = listUserId();
        userIds.stream().forEach(userId->{
            User user = getUser(userId);
            userList.add(user);
        });
        //获取用户列表 end

        return userList;
    };

    @Async
    @Override
    public Future<List<User>> listUser_2(){
        log.info("listUser_2 当前线程是：{}",Thread.currentThread().getName());
        //获取用户列表 start
        List<User> userList = new ArrayList<>();
        List<Integer> userIds = listUserId();
        if(CollUtil.isNotEmpty(userIds)){
            userIds.parallelStream().forEach(userId->{
                User user = getUser(userId);
                if(user!=null){
                    userList.add(user);
                }
            });
        }
        //获取用户列表 end
        return new AsyncResult<List<User>>(userList);
    };


    @Override
    public List<User> listUser_3(){
        //获取用户列表 start
        List<User> userList = new ArrayList<>();
        List<Integer> userIds = listUserId();
        if(CollUtil.isNotEmpty(userIds)){
            RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
            userIds.parallelStream().forEach(userId->{
                RequestContextHolder.setRequestAttributes(attributes);
                try {
                    User user = getUser(userId);
                    if(user!=null){
                        userList.add(user);
                    }
                }finally {
                    RequestContextHolder.resetRequestAttributes();
                }
            });
        }
        //获取用户列表 end

        return userList;
    };



    @Async(ExecutorConstant.simpleExecutor_3)
    @Override
    public Future<List<User>> listUser_4(){
        log.info("listUser_4 当前线程是：{}",Thread.currentThread().getName());
        //获取用户列表 start
        List<User> userList = new ArrayList<>();
        List<Integer> userIds = listUserId();
        if(CollUtil.isNotEmpty(userIds)){
            userIds.parallelStream().forEach(userId->{
                User user = getUser(userId);
                if(user!=null){
                    userList.add(user);
                }
            });
        }
        //获取用户列表 end
        return new AsyncResult<List<User>>(userList);
    };
}
